<template>
	<div class="clearfix">
		<a-upload
			@change="handleChange"
			:maxCount="props.uploadNumber"
			v-model:file-list="fileList"
			:headers="headers"
			accept="image"
			:action="action"
			list-type="picture-card"
			@remove="removeImage"
			@preview="handlePreview"
		>
			<div v-if="fileList.length < props.uploadNumber">
				<plus-outlined />
			</div>
		</a-upload>
		<a-modal title="" v-model:visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%; height: 200px" :src="previewImage" />
		</a-modal>
	</div>
</template>

<script setup name="uploadImageIndex">
	import tool from '@/utils/tool'

	import sysConfig from '@/config/index'
	const fileList = ref([])
	const emit = defineEmits({ uploadDone: null, uploadRemove: null })
	const headers = ref({
		token: tool.data.get('TOKEN')
	})

	const props = defineProps({
		action: {
			type: String,
			default: '/api/webapp/dev/file/uploadDynamicReturnUrl',
			required: false
		},
		// 上传数量
		uploadNumber: {
			type: Number,
			default: 1,
			required: false
		},
		files: {
			type: Array,
			default: () => {
				return []
			},
			required: false
		}
	})
	const action = sysConfig.API_URL + props.action

	const handleCancel = () => {
		previewVisible.value = false
	}
	const handlePreview = async (file) => {
		previewImage.value = file.url || file.response.data
		previewVisible.value = true
	}
	const previewVisible = ref(false)
	const previewImage = ref('')

	const removeImage = (file) => {
		let index = fileList.value.findIndex((it) => it['uid'] == file.uid)
		emit('uploadRemove', {
			index,
			url: file.url
		})
		return Promise.resolve(true)
	}
	// 上传时间，构造上传数组，主动推送至调用组件，单文件可以使用
	const handleChange = () => {
		// 单个文件可以使用回调方法，多个文件建议主动获取
		let result = []
		for (let a = 0; a < props.uploadNumber; a++) {
			const file = fileList.value[a]
			if (file && file.status === 'done' && file.response && file.response.code === 200) {
				const resultObj = {
					name: file.name,
					url: file.response.data
				}
				result.push(resultObj)
			}
		}
		if (result.length > 0) {
			emit('uploadDone', result)
		}
	}
	const setUploadFields = (files) => {
		fileList.value = files
	}
	// 通过DOM获取上传的文件
	const uploadFileList = () => {
		if (fileList.value) {
			const result = []
			// 只返回这些就够用了，其他基本用不到
			fileList.value.forEach((item) => {
				const obj = {
					name: item.name,
					type: item.type,
					size: item.size,
					url: item.url || item.response.data
				}
				result.push(obj)
			})
			return result
		} else {
			return []
		}
	}
	// 抛出这个获取文件列表的方法
	defineExpose({
		uploadFileList,
		setUploadFields
	})
</script>
<style scoped>
	.ant-upload-select-picture-card i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}
</style>
